/**
 * @name: http
 * @author: pengxiaoqi
 * @date: 2021/4/19 1:32 下午
 * @description：http
 * @update: 2021/4/19 1:32 下午
 */
import axios from 'axios'
import {Loading, Message} from 'element-ui'
import router from '../router/index.js'
import apiUrl from "../httpConfig/api";

let loading

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中....',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading() {
  loading.close()
}

export default function request(option, headers = {'Content-Type': 'application/json;charset=utf-8'}) {
  return new Promise((reslove, reject) => {
    const service = axios.create({
      baseURL: apiUrl,
      timeout: 30000,
      headers,
    });
// 请求拦截
    service.interceptors.request.use(
      (confing) => {
        startLoading()

        //设置请求头
        if (localStorage.Token) {
          confing.headers.access_token = localStorage.Token
        }

        return confing
      },
      (error) => {
        return Promise.reject(error)
      }
    )

//响应拦截

    service.interceptors.response.use(
      (response) => {
        endLoading()
        if (response.data.code === '0000' || toString.call(response.data) === '[object ArrayBuffer]' ) {

          return response.data
        } else if (response.data.code === '9795'||response.data.code === '9796'||response.data.code === '9797') {

          Message.error(response.data.msg)
          router.push({path: "/login"});
        } else {

          Message.error(response.data.msg)
        }

      },
      (error) => {
        Message.error('系统错误，请稍后重试')
        endLoading()
        return Promise.reject(error)
      }
    )
    service(option).then(res => {
      if (res) {
        reslove(res)
      }

    }).catch((err) => {
      reject(err)
    })

  })
}

